<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
        :immediate-check="false"
      >
        <!-- 文章列表 -->
        <article-item v-for="(item,index) in articleList" :key="item.art_id+index" :obj="item"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem'
import { articlesListAPI } from '@/api'
import { timeAgo } from '@/utils/date'
export default {
  props: {
    cid: Number
  },
  data() {
    return {
      isLoading: false,
      articleList: [], // 文章列表
      loading: false, // 底部加载状态
      finished: false, // 数据是否全部加载完成
      nextTime: null // 用于加载更多(分页)
    }
  },
  methods: {
    timeAgo: timeAgo,
    // 底部加载
    onLoad() {
      this.getArticleList()
    },
    async getArticleList() {
      const res = await articlesListAPI({
        channelId: this.cid,
        timestamp: this.nextTime
      })

      res.data.data.results.forEach(obj => {
        obj.pubdate = this.timeAgo(obj.pubdate)
      })
      if (res.data.data.results.length === 0) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.nextTime = res.data.data.pre_timestamp // 保存下一页数据的时间(做分页用)
        this.articleList = [...this.articleList, ...res.data.data.results]
        this.loading = false // 底部加载更多状态
      }
    },
    onRefresh() {
      this.nextTime = null
      this.articleList = []
      this.getArticleList()
      this.isLoading = false // 顶部加载状态关闭
    }
  },
  async created() {
    this.getArticleList()
  },
  components: {
    ArticleItem
  }
}
</script>
